<?php
namespace app\command;

use think\App;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;

abstract class Generate extends Command{

    abstract protected function getStub();

    protected function configure()
    {
        //后面会按照顺序取参数
        //$this->addArgument("age",Argument::REQUIRED,"the age of you");
        $this->addArgument("name",Argument::REQUIRED,"the name of class");
    }

    protected function execute(Input $input, Output $output)
    {
        $name = $input->getArgument("name");
        $className = $this->getClassName($name);
        $namespace = $this->getNameSpace($name);
        $path = $this->getClassPath($namespace);
        $file = $path.DS.$className.'.php';
        if (is_file($file)) {
            $output->writeln('<error> '.$className.' already exists!</error>');
            return false;
        }
        $this->createClass($className,$namespace,$file);
        $output->writeln($name." created");
    }

    protected function createClass($className,$namespace,$file){
        $stub = $this->getStub();
        $content = file_get_contents($stub);
        $content = str_replace("{%namespace%}",$namespace,$content);
        $content = str_replace("{%className%}",$className,$content);
        file_put_contents($file,$content);
    }

    protected function getNameSpace($name){
        $nameArr = explode("\\",$name);
        unset($nameArr[count($nameArr)-1]);
        $namespace = implode("\\",$nameArr);
        if($nameArr[0] != App::$namespace){
            $namespace = App::$namespace."\\".$namespace;
        }
        return $namespace;
    }

    protected function getClassName($name){
        $classNameArr = explode("\\",$name);
        $className = $classNameArr[count($classNameArr)-1];
        return $className;
    }

    protected function getClassPath($namespace){
        $pathArr = explode("\\",$namespace);
        unset($pathArr[0]);
        $path = implode(DS,$pathArr);
        $path = APP_PATH.$path;
        if(!is_dir($path)){
            mkdir(strtolower($path),0755,true);
        }
        return $path;
    }
}